import aliyunSignatureGenerator from './signature/AliyunSignatureGenerator';
import config from "./AliyunOSSConfig";
import axios from "axios";
import FileUploader from '../FileUploader';

function AliyunOSSFileUploader() {
    this.signatureGenerator = aliyunSignatureGenerator;
}

AliyunOSSFileUploader.prototype = Object.create(FileUploader);


AliyunOSSFileUploader.prototype.url = function (uploadPromise,originalName,newFileName) {
    return config.fileHost + '/' + newFileName;
};


AliyunOSSFileUploader.prototype.newFilename = function (file) {
    return file.name.split('.')[0] + Date.now();
};

AliyunOSSFileUploader.prototype.buildToken = function () {
    let signature = this.signatureGenerator.getSignature();
    let policy = this.signatureGenerator.getPolicyBase64();
    let ossAccessKeyId = config.OSSAccessKeyId;
    return {policy: policy, signature: signature, ossAccessKeyId: ossAccessKeyId}
};


AliyunOSSFileUploader.prototype.doUpload = function (token, newFileName, file) {

    let formData = new FormData();
    let parameters = {
        key: newFileName,//文件名称
        'OSSAccessKeyId': token.ossAccessKeyId,
        'policy': token.policy,
        'signature': token.signature,
        success_action_status: '200',
        file: file
    };
    for (let name in parameters) {
        formData.append(name, parameters[name])
    }


    let promise = axios.post(config.fileHost, formData);

    promise.then(function () {
        console.log("Upload successfully.");
    }, function (e) {
        console.log("Failed uploading:" + e);
    });
    return promise;
};


export default new AliyunOSSFileUploader()



